import React, { useEffect, useState } from 'react';
import { Progress, Card, Row, Col, Statistic, Spin } from 'antd';
import { Radar, Line } from 'react-chartjs-2';
import { useUserStore } from '../../store/userStore';
import { CarbonActivity } from '../../types';
import CarbonSaturnChart from './CarbonSaturnChart';
import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  Legend,
  RadialLinearScale,
  PointElement,
  LineElement,
  Filler,
  CategoryScale,
  LinearScale
} from 'chart.js';
import { 
  EnvironmentOutlined, 
  ApiOutlined, 
  ExperimentOutlined, 
  ThunderboltOutlined, 
  GoldOutlined 
} from '@ant-design/icons';

ChartJS.register(
  ArcElement, 
  Tooltip, 
  Legend, 
  RadialLinearScale, 
  PointElement, 
  LineElement, 
  Filler,
  CategoryScale,
  LinearScale
);

const PlanetEcoPanel: React.FC = () => {
  const { user, activities } = useUserStore();
  const [loading, setLoading] = useState(true);
  const [animate, setAnimate] = useState(false);

  // 加载动画效果
  useEffect(() => {
    setLoading(true);
    const timer = setTimeout(() => {
      setLoading(false);
      setAnimate(true);
    }, 1000);
    return () => clearTimeout(timer);
  }, []);

  // 获取星球状态数据
  const pollution = user?.planetState.pollution || 0;
  const biodiversity = user?.planetState.biodiversity || 0;
  const waterQuality = user?.planetState.waterQuality || 0;
  const greenEnergy = user?.greenEnergy || 0;
  const trees = user?.planetState.trees || 0;

  const getStatusColor = (value: number, isReverse: boolean = false) => {
    const threshold = isReverse ? 1 - value : value;
    if (threshold >= 0.8) return '#52c41a';
    if (threshold >= 0.6) return '#1890ff';
    if (threshold >= 0.4) return '#faad14';
    return '#f5222d';
  };

  // 准备饼图数据
  const typeData = {
    labels: ['交通', '能源', '食物', '废弃物'],
    datasets: [{
      data: [25, 30, 15, 30], // 模拟数据
      backgroundColor: [
        '#FF9800',
        '#2196F3',
        '#4CAF50',
        '#F44336'
      ],
      borderWidth: 0
    }]
  };

  // 雷达图数据
  const radarData = {
    labels: ['环境', '生物多样性', '水质', '绿色能源', '植被'],
    datasets: [
      {
        label: '当前状态',
        data: [
          (1 - pollution) * 100, 
          biodiversity * 100, 
          waterQuality * 100, 
          greenEnergy, 
          trees > 100 ? 100 : trees
        ],
        backgroundColor: 'rgba(82, 196, 26, 0.2)',
        borderColor: '#52c41a',
        pointBackgroundColor: '#52c41a',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: '#52c41a'
      },
      {
        label: '理想状态',
        data: [100, 100, 100, 100, 100],
        backgroundColor: 'rgba(24, 144, 255, 0.1)',
        borderColor: 'rgba(24, 144, 255, 0.5)',
        pointBackgroundColor: 'rgba(24, 144, 255, 0.5)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgba(24, 144, 255, 0.5)'
      }
    ]
  };

  // 获取当前日期所在的周一到周日
  const getCurrentWeekDates = () => {
    const now = new Date();
    const currentDay = now.getDay() || 7; // 将周日的0转换为7
    const monday = new Date(now);
    monday.setDate(now.getDate() - currentDay + 1);
    
    const weekDays = [];
    for (let i = 0; i < 7; i++) {
      const day = new Date(monday);
      day.setDate(monday.getDate() + i);
      weekDays.push(day);
    }
    return weekDays;
  };

  // 准备碳排放曲线数据
  const weekDays = getCurrentWeekDates();
  const carbonData = {
    labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    datasets: [{
      label: '碳排放量 (kg)',
      data: weekDays.map(date => {
        const dateStr = date.toISOString().split('T')[0];
        const dayActivity = activities?.find(a => new Date(a.date).toISOString().split('T')[0] === dateStr);
        return dayActivity ? dayActivity.value : 0;
      }),
      borderColor: '#52c41a',
      backgroundColor: 'rgba(82, 196, 26, 0.1)',
      tension: 0.4,
      fill: true
    }]
  };

  // 准备碳排放类型数据
  const carbonTypeData = [
    { label: '交通', value: 25, color: '#FF9800' },
    { label: '能源', value: 30, color: '#2196F3' },
    { label: '食物', value: 15, color: '#4CAF50' },
    { label: '废弃物', value: 30, color: '#F44336' }
  ];

  const totalEmission = carbonTypeData.reduce((sum, item) => sum + item.value, 0);

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '400px' }}>
        <Spin tip="正在加载星球生态数据..." size="large" />
      </div>
    );
  }

  return (
    <div className={animate ? 'fade-in' : ''} style={{ padding: '20px' }}>
      <style>
        {`
          .fade-in {
            animation: fadeIn 0.8s ease-in;
          }
          @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
          }
          .eco-card {
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            transition: all 0.3s ease;
          }
          .eco-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
          }
          .stat-icon {
            font-size: 20px;
            margin-right: 8px;
            padding: 8px;
            border-radius: 50%;
          }
        `}
      </style>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={12}>
          <Card 
            title="星球生态雷达图"
            className="eco-card"
            style={{ marginBottom: '24px' }}
            headStyle={{ fontSize: '16px', fontWeight: 'bold' }}
          >
            <div style={{ height: '300px' }}>
              <Radar 
                data={radarData} 
                options={{
                  responsive: true,
                  maintainAspectRatio: false,
                  scales: {
                    r: {
                      beginAtZero: true,
                      max: 100,
                      ticks: {
                        display: false
                      }
                    }
                  }
                }} 
              />
            </div>
          </Card>
        </Col>

        <Col xs={24} md={12}>
          <Card 
            title="碳排放趋势"
            className="eco-card"
            style={{ marginBottom: '24px' }}
            headStyle={{ fontSize: '16px', fontWeight: 'bold' }}
          >
            <div style={{ height: '300px' }}>
              <Line 
                data={carbonData}
                options={{
                  responsive: true,
                  maintainAspectRatio: false,
                  scales: {
                    y: {
                      title: {
                        display: true,
                        text: '碳排放量 (kg)'
                      }
                    }
                  },
                  plugins: {
                    legend: {
                      display: false
                    }
                  }
                }}
              />
            </div>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} md={8}>
          <Card className="eco-card">
            <Statistic
              title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <EnvironmentOutlined className="stat-icon" style={{ 
                    backgroundColor: `${getStatusColor(pollution, true)}20`,
                    color: getStatusColor(pollution, true)
                  }} />
                  环境污染指数
                </div>
              }
              value={(pollution * 100).toFixed(1)}
              precision={1}
              valueStyle={{ color: getStatusColor(pollution, true) }}
              suffix="%"
            />
            <Progress 
              percent={100 - pollution * 100} 
              showInfo={false}
              strokeColor={getStatusColor(pollution, true)}
              size="small"
              style={{ marginTop: 10 }}
            />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={8}>
          <Card className="eco-card">
            <Statistic
              title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <ApiOutlined className="stat-icon" style={{ 
                    backgroundColor: `${getStatusColor(biodiversity)}20`,
                    color: getStatusColor(biodiversity)
                  }} />
                  生物多样性
                </div>
              }
              value={(biodiversity * 100).toFixed(1)}
              precision={1}
              valueStyle={{ color: getStatusColor(biodiversity) }}
              suffix="%"
            />
            <Progress 
              percent={biodiversity * 100} 
              showInfo={false}
              strokeColor={getStatusColor(biodiversity)}
              size="small"
              style={{ marginTop: 10 }}
            />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={8}>
          <Card className="eco-card">
            <Statistic
              title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <ExperimentOutlined className="stat-icon" style={{ 
                    backgroundColor: `${getStatusColor(waterQuality)}20`,
                    color: getStatusColor(waterQuality)
                  }} />
                  水质纯净度
                </div>
              }
              value={(waterQuality * 100).toFixed(1)}
              precision={1}
              valueStyle={{ color: getStatusColor(waterQuality) }}
              suffix="%"
            />
            <Progress 
              percent={waterQuality * 100} 
              showInfo={false}
              strokeColor={getStatusColor(waterQuality)}
              size="small"
              style={{ marginTop: 10 }}
            />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={12}>
          <Card className="eco-card">
            <Statistic
              title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <ThunderboltOutlined className="stat-icon" style={{ 
                    backgroundColor: `${getStatusColor(greenEnergy/100)}20`,
                    color: getStatusColor(greenEnergy/100)
                  }} />
                  绿色能源
                </div>
              }
              value={greenEnergy}
              valueStyle={{ color: getStatusColor(greenEnergy/100) }}
              suffix="点"
            />
            <Progress 
              percent={(greenEnergy > 1000 ? 100 : greenEnergy/10)} 
              showInfo={false}
              strokeColor={getStatusColor(greenEnergy/100)}
              size="small"
              style={{ marginTop: 10 }}
            />
          </Card>
        </Col>

        <Col xs={24} sm={12} md={12}>
          <Card className="eco-card">
            <Statistic
              title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <GoldOutlined className="stat-icon" style={{ 
                    backgroundColor: `${getStatusColor(trees/100)}20`,
                    color: getStatusColor(trees/100)
                  }} />
                  森林覆盖
                </div>
              }
              value={trees}
              valueStyle={{ color: getStatusColor(trees/100) }}
              suffix="棵"
            />
            <Progress 
              percent={(trees > 100 ? 100 : trees)} 
              showInfo={false}
              strokeColor={getStatusColor(trees/100)}
              size="small"
              style={{ marginTop: 10 }}
            />
          </Card>
        </Col>
      </Row>

      <Card 
        title="碳排放类型分布" 
        className="eco-card"
        style={{ marginTop: '24px' }}
        headStyle={{ fontSize: '16px', fontWeight: 'bold' }}
      >
        <CarbonSaturnChart data={carbonTypeData} totalEmission={totalEmission} />
      </Card>
    </div>
  );
};

export default PlanetEcoPanel; 